import axios from "axios";
import { layer } from "@layui/layui-vue";
import { getToken } from "@/utils/auth";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import router from "@/router";

NProgress.configure({ showSpinner: false });

//错误提示
const StatusCodeMessage = {
  200: "请求成功",
  201: "",
  400: "请求错误(400)",
  401: "未授权,请重新登录(401)",
  403: "拒绝访问(403)",
  404: "请求出错(404)",
  408: "请求超时(408)",
  500: "服务器错误(500)",
  501: "服务未实现(501)",
  502: "网络错误(502)",
  503: "服务不可用(503)",
  504: "网络超时(504)",
};

const http = axios.create({
  baseURL: "/127.0.0.1", //使用代理-在vite.config.ts设置
  // baseURL: "/sp.6-7-8-9.com", //使用代理-在vite.config.ts设置
  // baseURL: "https://sp.6-7-8-9.com/pos1",
  timeout: 50000,
  //   requestOptions: {
  //     withToken: true,
  //   },
});

//数据请求拦截
http.interceptors.request.use(
  //1. 返回config对象
  //2. 可以设置携带token
  (config) => {
    NProgress.start(); //进度条
    config.headers = {
      "Content-Type": "application/json", //配置请求头
    };
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers["token"] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//返回响应数据拦截
http.interceptors.response.use(
  (response) => {
    // const { data } = response;
    // const { msg, code } = data;

    //token失效
    // if (code === 401) {
    //   NProgress.done();
    //   router.replace("/login");
    //   return Promise.reject(new Error("token失效"));
    // }

    // if (code !== 200) {
    // NProgress.done();
    // if (msg.length <= 15) {
    //   layer.notify({
    //     title: "Error",
    //     content: msg || "服务器端异常",
    //     icon: 2,
    //   });
    // } else {
    //   layer.msg(msg || "服务器端异常", { icon: 2, time: 1000 });
    // }
    // return Promise.reject(new Error("Error"));
    // }

    NProgress.done();
    return response;
  },
  (error) => {
    NProgress.done();
    layer.closeAll();
    const response = Object.assign({}, error.response);
    response &&
      layer.notify({
        title: "Error",
        content:
          StatusCodeMessage[response.status] ||
          "系统异常,请检查网络或者联系管理员!",
        icon: 2,
      });
    return Promise.reject(error);
  }
);

const requset = (config) => {
  return new Promise((resolve, reject) => {
    http
      .request(config)
      .then((res) => resolve(res.data))
      .catch((err) => {
        reject(err);
      });
  });
};

requset.get = (url, params, headers) => {
  return requset({
    method: "get",
    url,
    params,
    headers,
  });
};

requset.post = (url, params, headers) => {
  return requset({
    method: "post",
    url,
    data: params,
    headers,
  });
};

export default requset;
